"""
主题: 创建一个线程池
问题: 你创建一个工作者线程池，用来响应客户端请求或执行其他的工作。
提示 : 
"""

from socket import AF_INET, SOCK_STREAM, socket
from concurrent.futures import ThreadPoolExecutor
import threading
import time

def echo_client(sock, client_addr):
    '''
    Handle a client connection
    '''
    print('[{}]Got connection from {}\n'.format(threading.current_thread().name, client_addr))
    while True:
        msg = sock.recv(65536)
        if not msg:
            break
        # sock.sendall(msg)
        # 模拟业务处理
        time.sleep(0.3)
        print("msg:{}\n".format(int.from_bytes(msg, 'little')), end = "")

    print('Client closed connection\n')
    sock.close()

def echo_server(addr):
    pool = ThreadPoolExecutor(128)
    sock = socket(AF_INET, SOCK_STREAM)
    sock.bind(addr)
    sock.listen(5)
    while True:
        client_sock, client_addr = sock.accept()
        pool.submit(echo_client, client_sock, client_addr)

echo_server(('',20001))